package com.googlecode.genproject.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 文件处理类
 * @author devilishking
 *
 */
public class FileUtil {
	private static final String ENCODING = "UTF-8";
	private static final Log log = LogFactory.getLog(FileUtil.class);
	
	/**
	 * 创建文件夹
	 * @param path 文件夹绝对路径
	 */
	public static String makeDirectory(String path){
		File file = new File(path);		
		file.mkdir();
		return path;
	}

	/** 
	 * 多级目录创建
	 * @param  folderPath 准备要在本级目录下创建新目录的目录路径 例如 c:myf
	 * @param  paths 	     无限级目录参数，各级目录以单数线区分 例如 a|b|c
	 * @return  		      返回创建文件后的路径 例如 c:myf/a/b/c
	 */
	public static String makeDirectories(String folderPath, String paths) throws Exception{
		String txts = folderPath;
		String txt;
		txts = folderPath;
		StringTokenizer st = new StringTokenizer(paths, "|");
		while(st.hasMoreTokens()){
			txt = st.nextToken().trim();
			if (txts.lastIndexOf("/") != -1) {
				txts = makeDirectory(txts + txt + "/");
			} else {
				txts = makeDirectory(txts + txt + "/");
			}
		}
		return txts;
	}

	/** 
	 * 有编码方式的文件创建
	 * @param  filePath    文本文件完整绝对路径及文件名
	 * @param  fileContent 文本文件内容
	 * @return 
	 */
	public static void createFile(String filePath, String fileContent) throws Exception{
		File myFilePath = new File(filePath);
		if (!myFilePath.exists()) {
			myFilePath.getParentFile().mkdirs();
			myFilePath.createNewFile();
		}
		PrintWriter myFile = new PrintWriter(myFilePath, ENCODING);
		String strContent = fileContent;
		myFile.println(strContent);
		myFile.close();
	}

	/**
	 * 读取存入文件内的信息
	 * @param filePath     文件路径
	 * @param dataTitle    信息标题
	 * @param absolutePath 系统绝对路径
	 * @return
	 * @throws FileNotFoundException
	 * @throws Exception
	 */
	public static String readFileData(String filePath, String dataTitle, String absolutePath) throws Exception{
		StringBuffer content = new StringBuffer();
		FileReader fr = null;
		BufferedReader br = null;
		try{
			InputStreamReader isr = new InputStreamReader(new FileInputStream(absolutePath+filePath), ENCODING);   
            br = new BufferedReader(isr);
            while (br.ready()) {
            	content.append(br.readLine());
            }
            return content.toString();
		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new Exception("信息[" + dataTitle + "]存放文件["
								+ filePath +"]已丢失!\r\n详细错误信息为:" 
								+ e.getMessage());
		}
		catch (Exception e) {
			throw e;
		}
		finally{
			if (br != null){
				br.close();
			}
			if (fr != null){
				fr.close();
			}
		}
	}
	
	/**
	 * 复制文件
	 * @param srcFilePath    源文件路径
	 * @param targetFilePath 目标文件路径
	 * @throws Exception
	 */
	public static void copyFile(String srcFilePath, String targetFilePath) throws Exception{
		BufferedInputStream is = null;
        BufferedOutputStream os = null;
        try{
             is = new BufferedInputStream(new FileInputStream(srcFilePath));
             os = new BufferedOutputStream(new FileOutputStream(targetFilePath));
             
             byte[] b = new byte[1024 * 5];  
             int len;  
             while ((len =is.read(b)) != -1) {  
            	 os.write(b, 0, len);  
             }  
             os.flush();  
        }
        finally{
        	if (is != null) is.close();
        	if (os != null) os.close();
        }
	}
	
	/**
	 * 复制文件夹
	 * @param srcDirectioryPath    源文件夹
	 * @param targetDirectioryPath 目标文件夹
	 * @throws Exception
	 */
	public static void copyDirectiory(String srcDirectioryPath, String targetDirectioryPath) throws Exception{
		(new File(targetDirectioryPath)).mkdirs();  
		File[] file = (new File(srcDirectioryPath)).listFiles();  
		if (file == null) return;
        for (int i = 0; i < file.length; i++) {  
            if (file[i].isFile()) {  
                File sourceFile=file[i];  
              	File targetFile=new File(new File(targetDirectioryPath).getAbsolutePath()+File.separator+file[i].getName());  
                copyFile(sourceFile.getAbsolutePath(), targetFile.getAbsolutePath());  
            }  
            if (file[i].isDirectory()) {  
                String dir1=srcDirectioryPath + "/" + file[i].getName(); 
                String dir2=srcDirectioryPath + "/"+ file[i].getName();  
                copyDirectiory(dir1, dir2);  
            }  
        }
	}
	
	/**
	 * 根据URL地址删除文件
	 * @param url 文件绝对路径
	 * @throws Exception
	 */
	public static void deleteFile(String url) throws Exception{
		File file = new File(url);
		file.delete();
	}
	
	/**
	 * 批删除文件组（不抛出异常）
	 * @param urlsList 文件组（相对路径）
	 */
	public static void deleteFiles(List<String> urlsList){
		for(int i = 0; i < urlsList.size(); i++){
			try{
				deleteFile(urlsList.get(i).toString());
			}
			catch(Exception e){
				log.error(urlsList.get(i).toString() + "throw Exception(\n" + e.getMessage() + "\n)");
				continue;
			}
		}
	}
	
	/**
	 * 删除文件夹
	 * @param path 文件夹绝对路径
	 */
	public static void deleteDirectory(String path) throws Exception{
		File file = new File(path);
		if(file.exists() && file.isDirectory()){
			File[] delFiles = file.listFiles();
			for(int i = 0; i < delFiles.length; i++){
				deleteDirectory(delFiles[i].getAbsolutePath());
			}
		}
		file.delete();
	}
}
